use std::thread;
use std::time::Duration;
use std::sync::mpsc;

pub fn main() {
    // let handle = thread::spawn(move || {
    //     for i in 0..10 {
    //         println!("hi number {} from the spawned thread", i);
    //         thread::sleep(Duration::from_secs(1));
    //     }
    // });
    //
    // for i in 0..5 {
    //     println!("hi number {} from the main thread", i);
    //     thread::sleep(Duration::from_secs(1));
    // }
    // handle.join();

    // ==================================================
    // let v = vec![1, 2, 3];
    // let handle = thread::spawn(move || {
    //     println!("vector: {:?}", &v);
    // });

    // 消息传递
    // ==================================================

    // 传递单个值
    // let (tx, rx) = mpsc::channel();
    //
    // thread::spawn(move || {
    //     let val = String::from("hi");
    //     tx.send(val).unwrap();
    // });
    //
    // let received = rx.recv().unwrap();
    // println!("Got: {}", received);

    // 传递多个值
    let (tx,rx) = mpsc::channel();
    let tx1  = mpsc::Sender::clone(&tx);

    thread::spawn(move || {
        let vals = vec![
            String::from("1: hi"),
            String::from("1: from"),
            String::from("1: the"),
            String::from("1: thread"),
        ];

        for val in vals {
            tx1.send(val).unwrap();
            thread::sleep(Duration::from_millis(200));
        }
    });


    thread::spawn(move || {
        let vals = vec![
            String::from("2: hi"),
            String::from("2: from"),
            String::from("2: the"),
            String::from("2: thread"),
        ];

        for val in vals {
            tx.send(val).unwrap();
            thread::sleep(Duration::from_millis(200));
        }
    });

    for received in rx {
        println!("Gpt: {}", received);
    }

}
